<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/my-blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/my-blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/my-blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/my-blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/my-blog/css/main.css">


<link rel="stylesheet" href="/my-blog/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"mmx1960.gitee.io","root":"/my-blog/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta property="og:type" content="website">
<meta property="og:title" content="a new develop starter">
<meta property="og:url" content="http://mmx1960.gitee.io/my-blog/index.html">
<meta property="og:site_name" content="a new develop starter">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="zichao">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://mmx1960.gitee.io/my-blog/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : true,
    isPost : false,
    lang   : 'zh-CN'
  };
</script>

  <title>a new develop starter</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<style>mjx-container[jax="SVG"] {
  direction: ltr;
}

mjx-container[jax="SVG"] > svg {
  overflow: visible;
}

mjx-container[jax="SVG"] > svg a {
  fill: blue;
  stroke: blue;
}

mjx-container[jax="SVG"][display="true"] {
  display: block;
  text-align: center;
  margin: 1em 0;
}

mjx-container[jax="SVG"][justify="left"] {
  text-align: left;
}

mjx-container[jax="SVG"][justify="right"] {
  text-align: right;
}

g[data-mml-node="merror"] > g {
  fill: red;
  stroke: red;
}

g[data-mml-node="merror"] > rect[data-background] {
  fill: yellow;
  stroke: none;
}

g[data-mml-node="mtable"] > line[data-line] {
  stroke-width: 70px;
  fill: none;
}

g[data-mml-node="mtable"] > rect[data-frame] {
  stroke-width: 70px;
  fill: none;
}

g[data-mml-node="mtable"] > .mjx-dashed {
  stroke-dasharray: 140;
}

g[data-mml-node="mtable"] > .mjx-dotted {
  stroke-linecap: round;
  stroke-dasharray: 0,140;
}

g[data-mml-node="mtable"] > svg {
  overflow: visible;
}

[jax="SVG"] mjx-tool {
  display: inline-block;
  position: relative;
  width: 0;
  height: 0;
}

[jax="SVG"] mjx-tool > mjx-tip {
  position: absolute;
  top: 0;
  left: 0;
}

mjx-tool > mjx-tip {
  display: inline-block;
  padding: .2em;
  border: 1px solid #888;
  font-size: 70%;
  background-color: #F8F8F8;
  color: black;
  box-shadow: 2px 2px 5px #AAAAAA;
}

g[data-mml-node="maction"][data-toggle] {
  cursor: pointer;
}

mjx-status {
  display: block;
  position: fixed;
  left: 1em;
  bottom: 1em;
  min-width: 25%;
  padding: .2em .4em;
  border: 1px solid #888;
  font-size: 90%;
  background-color: #F8F8F8;
  color: black;
}

foreignObject[data-mjx-xml] {
  font-family: initial;
  line-height: normal;
  overflow: visible;
}

.MathJax path {
  stroke-width: 3;
}

mjx-container[display="true"] {
  overflow: auto hidden;
}

mjx-container[display="true"] + br {
  display: none;
}
</style></head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/my-blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">a new develop starter</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/my-blog/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/my-blog/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/my-blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-base">

    <a href="/my-blog/categories/%E5%9F%BA%E7%A1%80/" rel="section"><i class="fa fa-fw fa-sitemap"></i>基础</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content index posts-expand">
            
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://mmx1960.gitee.io/my-blog/2020/09/20/bst-in-action/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/my-blog/images/avatar.gif">
      <meta itemprop="name" content="zichao">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="a new develop starter">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/my-blog/2020/09/20/bst-in-action/" class="post-title-link" itemprop="url">BST(二叉搜索树)总结和算法实践</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-09-20 22:50:23 / 修改时间：23:46:31" itemprop="dateCreated datePublished" datetime="2020-09-20T22:50:23+08:00">2020-09-20</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/my-blog/categories/%E5%9F%BA%E7%A1%80/" itemprop="url" rel="index"><span itemprop="name">基础</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="性质"><a href="#性质" class="headerlink" title="性质"></a>性质</h2><ol>
<li>具有二叉树的基本特性</li>
<li>没有节点为空树</li>
<li>左子树上所有节点都比根节点小</li>
<li>右子树上所有节点都比根节点大</li>
</ol>
<h2 id="操作"><a href="#操作" class="headerlink" title="操作"></a>操作</h2><h3 id="遍历"><a href="#遍历" class="headerlink" title="遍历"></a>遍历</h3><p>普通树的遍历方式同样适用于二叉搜索树，有前序遍历、中序遍历、后序遍历。<br>在二叉搜索树中，这三种不同的遍历方式对应一些不同的特性。</p>
<h4 id="前序遍历"><a href="#前序遍历" class="headerlink" title="前序遍历"></a>前序遍历</h4><p>口诀：根左右</p>
<p>图例：</p>
<img src="/my-blog/2020/09/20/bst-in-action/pre-order.png" class title="This is an example image">
<h4 id="中序遍历"><a href="#中序遍历" class="headerlink" title="中序遍历"></a>中序遍历</h4><p>口诀：左根右</p>
<p>图例：</p>
<img src="/my-blog/2020/09/20/bst-in-action/in-order.png" class title="This is an example image">
<p>根据性质3、4，可以知道中序遍历中，节点的值是不断递增的。</p>
<h4 id="后序遍历"><a href="#后序遍历" class="headerlink" title="后序遍历"></a>后序遍历</h4><p>口诀：左右根</p>
<p>图例：</p>
<img src="/my-blog/2020/09/20/bst-in-action/post-order.png" class title="This is an example image">
<h4 id="FrameCode"><a href="#FrameCode" class="headerlink" title="FrameCode"></a>FrameCode</h4><p>三种遍历方法都可以用一种模板来编写。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">traverse</span><span class="params">(TreeNode root)</span> </span>{</span><br><span class="line">       <span class="keyword">if</span> (root == <span class="keyword">null</span>) {</span><br><span class="line">           <span class="keyword">return</span>;</span><br><span class="line">       }</span><br><span class="line">       <span class="comment">//前序遍历</span></span><br><span class="line">       traverse(root.left);</span><br><span class="line">       <span class="comment">//中序遍历</span></span><br><span class="line">       traverse(root.right);</span><br><span class="line">       <span class="comment">//后序遍历</span></span><br><span class="line">   }</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="实践"><a href="#实践" class="headerlink" title="实践"></a>实践</h3><h4 id="二叉搜索树个数-LeetCode-96"><a href="#二叉搜索树个数-LeetCode-96" class="headerlink" title="二叉搜索树个数(LeetCode#96)"></a>二叉搜索树个数(LeetCode#96)</h4><p><strong>描述：</strong> 给出个数n,求不重复的二叉搜索树的个数。</p>
<p>根据二叉搜索树的性质，除去根节点，可以划分左子树和右子树的数量，得到不同的二叉搜索树，每个树都不一样。</p>
<p>比如：n=1时，只有一种划分方法：0左子树的个数 <em> 0右子树的个数，n=2时，有两种划分方法：0左子树的个数 </em> 1右子树的个数，1左子树的个数 * 0右子树的个数。</p>
<p>依次类推，我们可以得到计算公式，是一个分段函数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">L(n)= \begin{cases}</span><br><span class="line">        1 &amp; n = 0\\\\</span><br><span class="line">        \sum_{i=1}^{n} L(i-1) \times L(n-i), &amp; n &gt; 0\\\\</span><br><span class="line">    \end{cases}</span><br></pre></td></tr></table></figure>
<p>很快我们可以写出代码，分段函数的代码类似斐波拉契函数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">class Solution {</span><br><span class="line">    public int numTrees(int n) {</span><br><span class="line">        if (n == 0){</span><br><span class="line">            return 1;</span><br><span class="line">        }</span><br><span class="line">        int sum = 0;</span><br><span class="line">        for (int i = 1; i &lt;= n; i++) {</span><br><span class="line">            sum += numTrees(i -1) * numTrees(n - i);</span><br><span class="line">        }</span><br><span class="line">        return sum;</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<p><strong>优化</strong></p>
<p>这种代码运用递归，有很多冗余计算，我们可以用缓存来减少遍历次数，从而减少计算量，提升性能。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">class Solution {</span><br><span class="line">    int[] cache;</span><br><span class="line">    public int numTrees(int n) {</span><br><span class="line">        cache = new int[n + 1];</span><br><span class="line">        cache[0] = 1;</span><br><span class="line">        for (int j = 1; j &lt;= n; j++) {</span><br><span class="line">            for (int i = 1; i &lt;= j; i++) {</span><br><span class="line">                cache[j] += cache[i - 1] * cache[j - i];</span><br><span class="line">            }</span><br><span class="line">        }</span><br><span class="line">        return cache[n];</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<img src="/my-blog/2020/09/20/bst-in-action/result.png" class title="This is an example image">
<p>有兴趣的同学可以尝试下。</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://mmx1960.gitee.io/my-blog/2020/09/20/merge-sort/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/my-blog/images/avatar.gif">
      <meta itemprop="name" content="zichao">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="a new develop starter">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/my-blog/2020/09/20/merge-sort/" class="post-title-link" itemprop="url">归并排序算法总结</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-09-20 22:38:10 / 修改时间：22:41:11" itemprop="dateCreated datePublished" datetime="2020-09-20T22:38:10+08:00">2020-09-20</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/my-blog/categories/%E5%9F%BA%E7%A1%80/" itemprop="url" rel="index"><span itemprop="name">基础</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="归并排序"><a href="#归并排序" class="headerlink" title="归并排序"></a>归并排序</h2><p>归并排序在现代计算机系统中用处颇多，尤其是在大文件排序这块。像mysql等数据库系统也都实现了归并排序算法。</p>
<h3 id="算法思路"><a href="#算法思路" class="headerlink" title="算法思路"></a>算法思路</h3><p>归并排序的核心思想，是把两个有序数列(数组)合并成一个更大的有序数列。</p>
<p>那么对于一个无序的数组，我们怎么找到这两个有序数组呢？</p>
<p>这时候就有两种方式：自顶向下和自底向上两种。</p>
<h4 id="自顶向下"><a href="#自顶向下" class="headerlink" title="自顶向下"></a>自顶向下</h4><p>自定向下就是对于一个数组，如果我们可以把它按中间的点分为两部分，左半边和右半边，如果左半边和右半边都是有序的，那么就可以直接对两部分进行合并，所以需要对左半边进行排序，然后对右半边排序，最后把左右两边合并成一个新的数组。</p>
<p>同时，这个过程是可以一直递归的执行下去的，直到数组的元素为1，这样就不用排序，直接可以认为他是有序的。</p>
<p>那么我们可以定义：</p>
<ul>
<li>一个无序数组 <code>int[] a;</code></li>
<li>数组的第一个元素位置 <code>int low;</code></li>
<li>数组的中间的元素位置 <code>int mid;</code></li>
<li>数组的最后一个元素位置 <code>int high;</code></li>
<li>合并操作的方法定义 <code>void merge(int[] a,int low,int mid,int high);</code></li>
</ul>
<p>sort操作的伪代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">sort</span><span class="params">(<span class="keyword">int</span>[] a,<span class="keyword">int</span> low,<span class="keyword">int</span> high)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(hight &lt;= low)&#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> mid = low + (high - low)/<span class="number">2</span>;</span><br><span class="line">    sort(a,low,mid);</span><br><span class="line">    sort(a,mid+<span class="number">1</span>,high);</span><br><span class="line">    merge(a,low,mid,high);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="自底向上"><a href="#自底向上" class="headerlink" title="自底向上"></a>自底向上</h4><p>自底向上的方法，时间效率上和自顶向下没太大差别，更多的是一种思考方式上的不同。</p>
<p>对于一个无序数组，我们可以先一一merge，这样可以得到两个两个都有序的数组，然后在两两merge，这样可以得到四个四个都有序的数组，依次类推，直到整个数组都为有序。</p>
<p>sort操作的伪代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">sort</span><span class="params">(<span class="keyword">int</span>[] a)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> N = a.length;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> sz = <span class="number">1</span>;sz &lt; N ;sz = sz+sz)&#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> low = <span class="number">0</span>;low &lt; N - sz; low+=sz+sz)&#123;</span><br><span class="line">            merge(a,low,low+sz-<span class="number">1</span>,Math.min(lo+sz+sz-<span class="number">1</span>,N-<span class="number">1</span>));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="归并操作"><a href="#归并操作" class="headerlink" title="归并操作"></a>归并操作</h3><h4 id="简单归并"><a href="#简单归并" class="headerlink" title="简单归并"></a>简单归并</h4><p>常规的归并操作比较简单，就和把大象放到冰箱里有几个步骤是一样的</p>
<ol>
<li>定义一个新数组t，长度为high - low + 1</li>
<li>定义新数组的位置索引ti</li>
<li>定义两个变量li 、hi，分别维护原数组两个部分的位置索引</li>
<li>遍历ti 从 0 到 数组长度 - 1，分别比较原数组两个部分索引对应元素的大小，小的那个放到新数组中，并且索引+1</li>
<li>如果原数组的其中一部分用完，则把另一部分一次放入新数组中</li>
</ol>
<p>伪代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">int</span>[] merge(<span class="keyword">int</span> a[] , <span class="keyword">int</span> low, <span class="keyword">int</span> mid ,<span class="keyword">int</span> high)&#123;</span><br><span class="line">    <span class="keyword">int</span>[] t = <span class="keyword">new</span> <span class="keyword">int</span>[high - low + <span class="number">1</span>];</span><br><span class="line">    <span class="keyword">int</span> ti = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> li = low,hi = mid + <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">while</span>(ti &lt; t.lenght)&#123;</span><br><span class="line">        <span class="keyword">if</span>(li &lt;= mid &amp;&amp; hi &lt;= high)&#123;</span><br><span class="line">            <span class="keyword">if</span>(a[li] &lt; a[hi])&#123;</span><br><span class="line">                t[ti++] = a[li++];</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                t[ti++] = a[hi++];</span><br><span class="line">            &#125;</span><br><span class="line">            </span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">while</span>(li &lt;= mid)&#123;</span><br><span class="line">                t[ti++] = a[li++];</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">while</span>(hi &lt;= high)&#123;</span><br><span class="line">                t[ti++] = a[hi++];</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> t;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="空间优化"><a href="#空间优化" class="headerlink" title="空间优化"></a>空间优化</h4><p>细心的同学可能会说：你这上面的merge方法和之前排序时定义的merge方法不一样啊，排序的时候，merge直接就在原数组中合并了。</p>
<p>是这样的，上面merge的方法有他的缺陷，每次merge都要生成新的数组，这样空间占用会很大，所以下面介绍一种原地归并的方法，减少数组分配的次数。</p>
<h5 id="原地归并"><a href="#原地归并" class="headerlink" title="原地归并"></a>原地归并</h5><p>原地归并需要在排序的最开始生成一个和需要排序的数组的拷贝。后续归并操作的时候，需要用到这个数组，来达到原地归并的目的。这样空间占用就小很多，不用每次merge生成一个新数组。</p>
<p>对于每次merge的过程中，分为四种情况来处理：</p>
<ul>
<li>左半边元素用尽，取右半边的元素</li>
<li>右半边元素用尽，取左半边的元素</li>
<li>左边元素比右边元素大，取右半边的元素</li>
<li>右边元素比左边元素大，取左半边的元素</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span>[] copyA = <span class="keyword">int</span> [a.lenght];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">merge</span><span class="params">(<span class="keyword">int</span> a[] , <span class="keyword">int</span> low, <span class="keyword">int</span> mid ,<span class="keyword">int</span> high)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> li = low,hi = mid + <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> k = low;k &lt;= high;k++)&#123;</span><br><span class="line">        copyA[k] = a[k];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> k = low;k &lt;= high;k++)&#123;</span><br><span class="line">        <span class="keyword">if</span>(li &gt; mid)&#123;</span><br><span class="line">            a[k] = copyA[hi++];</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span>(hi &gt; high)&#123;</span><br><span class="line">            a[k] = copyA[li++];</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span>(copyA[li] &gt; copyA[hi])&#123;</span><br><span class="line">            a[k] = copyA[hi++];</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span>(copyA[li] &lt; copyA[hi])&#123;</span><br><span class="line">            a[k] = copyA[li++];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h3><p><a target="_blank" rel="noopener" href="https://book.douban.com/subject/19952400/">算法（第4版） 塞奇威克 (Robert Sedgewick) / 韦恩 (Kevin Wayne)</a></p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  


  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">zichao</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/my-blog/archives/">
        
          <span class="site-state-item-count">2</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">分类</span>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/my-blog/tags/">
          
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zichao</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/my-blog/lib/anime.min.js"></script>
  <script src="/my-blog/lib/velocity/velocity.min.js"></script>
  <script src="/my-blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/my-blog/js/utils.js"></script>

<script src="/my-blog/js/motion.js"></script>


<script src="/my-blog/js/schemes/pisces.js"></script>


<script src="/my-blog/js/next-boot.js"></script>




  















  

  
      

<script>
  if (typeof MathJax === 'undefined') {
    window.MathJax = {
      loader: {
        source: {
          '[tex]/amsCd': '[tex]/amscd',
          '[tex]/AMScd': '[tex]/amscd'
        }
      },
      tex: {
        inlineMath: {'[+]': [['$', '$']]},
        tags: 'ams'
      },
      options: {
        renderActions: {
          findScript: [10, doc => {
            document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
              const display = !!node.type.match(/; *mode=display/);
              const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
              const text = document.createTextNode('');
              node.parentNode.replaceChild(text, node);
              math.start = {node: text, delim: '', n: 0};
              math.end = {node: text, delim: '', n: 0};
              doc.math.push(math);
            });
          }, '', false],
          insertedScript: [200, () => {
            document.querySelectorAll('mjx-container').forEach(node => {
              let target = node.parentNode;
              if (target.nodeName.toLowerCase() === 'li') {
                target.parentNode.classList.add('has-jax');
              }
            });
          }, '', false]
        }
      }
    };
    (function () {
      var script = document.createElement('script');
      script.src = '//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML';
      script.defer = true;
      document.head.appendChild(script);
    })();
  } else {
    MathJax.startup.document.state(0);
    MathJax.texReset();
    MathJax.typeset();
  }
</script>

    

  

</body>
</html>
